<template>
  <div>
    <div v-if="pageName === 'list'">
      <!-- 上面工单数量 -->
      <div class="banner">
        <div class="left" @click="queryTable('left')">
          <img :src="blueFill" alt="今日解隔离工单" />
          <div class="title">
            <p>今日解隔离工单</p>
            <p>
              <span>{{ sumValue.finishCount }}/{{ sumValue.totalCount }}</span>
            </p>
          </div>
        </div>
        <div class="middle" @click="queryTable('middle')">
          <img :src="yellowFill" alt="今日未完成工单" />
          <div class="title">
            <p>今日未完成工单</p>
            <p>{{ sumValue.unFinishCount }}</p>
          </div>
        </div>
        <div class="right" @click="queryTable('right')">
          <img :src="redFill" alt="历史未执行工单" />
          <div class="title">
            <p>历史未执行工单</p>
            <p>{{ sumValue.unStartCount }}</p>
          </div>
        </div>
      </div>
      <div class="equip-wrap-common">
        <px-form ref="searchFormRef" class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
          <!-- 条件搜索 -->
          <px-row :gutter="22">
            <px-col :span="6">
              <px-form-item label="工单编号" prop="workOrderNo">
                <px-input
                  v-model="queryParams.workOrderNo"
                  placeholder="请输入工单编号"
                  maxlength="50"
                  @blur="queryParams.workOrderNo = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="创建人" prop="creator">
                <px-select-v2 v-model="queryParams.creator" filterable clearable :options="contactNameList" placeholder="请选择" />
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="执行人" prop="executor">
                <px-select-v2 v-model="queryParams.executor" filterable clearable :options="contactNameListPlus" placeholder="请选择" />
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="设备状态" prop="taskStatusKey">
                <px-select
                  v-model="queryParams.taskStatusKey"
                  placeholder="请选择设备状态"
                  clearable
                  filterable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  :max-collapse-tags="2"
                >
                  <px-option v-for="(item, index) in taskStatusKeyList" :key="index" :label="item.label" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="隔离计划开始时间" prop="startTime">
                <px-date-picker
                  v-model="queryParams.startTime"
                  style="width: 100%"
                  placeholder="请选择开始时间"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :clearable="false"
                  @change="changeStartTime"
                />
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="隔离计划结束时间" prop="endTime	">
                <px-date-picker
                  v-model="queryParams.endTime"
                  style="width: 100%"
                  placeholder="请选择结束时间"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :clearable="false"
                  @change="changeEndTime"
                />
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="工单完成时间" prop="time">
                <px-date-picker
                  v-model="queryParams.time"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-button type="primary" @click="queryTable">查询</px-button>
              <px-button @click="resetTable">重置</px-button>
            </px-col>
          </px-row>
        </px-form>
        <!-- 表格功能 -->
        <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 440px)" border>
          <px-table-column label="序号" min-width="50" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column prop="workOrderNo" label="工单编号" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              <span class="workOrderNo" @click="clickEqpId(scope.row)">{{ scope.row.workOrderNo }}</span>
            </template>
          </px-table-column>
          <px-table-column prop="taskStatusKeyDesc" label="工单状态" min-width="150" show-overflow-tooltip>
            <template #default="scope">
              <p
                class="status"
                :style="{
                  color: `${tagColorList[scope.row.taskStatusKeyDesc]}`,
                  border: `1px solid ${tagBorderColorList[scope.row.taskStatusKeyDesc]}`,
                  backgroundColor: `${tagBgColorList[scope.row.taskStatusKeyDesc]}`
                }"
              >
                <span>{{ scope.row.taskStatusKeyDesc }}</span>
              </p>
            </template>
          </px-table-column>
          <px-table-column prop="startTime" label="隔离计划开始时间" min-width="200" show-overflow-tooltip />
          <px-table-column prop="endTime" label="隔离计划结束时间" min-width="200" show-overflow-tooltip />
          <px-table-column prop="creatorName" label="工单创建人" min-width="180" show-overflow-tooltip />
          <px-table-column prop="executorName" label="隔离执行人" min-width="180" show-overflow-tooltip />
          <px-table-column prop="completedTime" label="工单完成时间" min-width="240" show-overflow-tooltip />
          <px-table-column fixed="right" label="操作" min-width="200" align="center">
            <template #default="scope">
              <px-button
                v-has="'ERC_ALARM_CLEAR'"
                :disabled="!GL_CODES.includes(scope.row.taskStatusKey)"
                link
                type="primary"
                @click="handleView(scope.row)"
                >一键隔离</px-button
              >
              <px-button
                v-has="'ERC_MAINTAIN_HISTORY_DETAIL'"
                :disabled="!JGL_CODES.includes(scope.row.taskStatusKey)"
                link
                type="primary"
                @click="handleView(scope.row)"
              >
                一键解隔离
              </px-button>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="tableData.length !== 0 && total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="equip-table-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
    <DetailPage v-if="pageName === 'detail'" v-model="pageName" v-model:source="source" :currentData="currentData" />
    <EditPage v-if="pageName === 'edit'" v-model="pageName" :source="source" :currentData="currentData" />
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "ERC_ALARM_REALTIME"
});
import { getAlarmCount, list } from "@/api/erc/detector";
import { searchTreeLedger } from "@/api/erc/equip";
import blueFill from "@/assets/images/materialType/blueFill.png";
import redFill from "@/assets/images/materialType/redFill.png";
import yellowFill from "@/assets/images/materialType/yellowFill.png";
import DetailPage from "./detail.vue";
import EditPage from "./edit.vue";

import { stringTrimOfParams } from "@/utils/common";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { onMounted, reactive, toRefs, watch } from "vue";
import { GL_CODES, JGL_CODES, tagBgColorList, tagBorderColorList, tagColorList } from "./const";

// 获取当前日期
const startnow = new Date();
// 设置时间为当天的 00:00:00
const startOfDay = new Date(startnow.getFullYear(), startnow.getMonth(), startnow.getDate(), 0, 0, 0);
// 获取年、月、日
const startyear = startOfDay.getFullYear();
const startmonth = String(startOfDay.getMonth() + 1).padStart(2, "0"); // 月份从 0 开始，需要 +1
const startday = String(startOfDay.getDate()).padStart(2, "0"); // 补零
// 获取时、分、秒（固定为 00:00:00）
const starthours = String(startOfDay.getHours()).padStart(2, "0"); // 补零
const startminutes = String(startOfDay.getMinutes()).padStart(2, "0"); // 补零
const startseconds = String(startOfDay.getSeconds()).padStart(2, "0"); // 补零
// 格式化为 YYYY-MM-DD HH:MM:SS
const startformattedTime = `${startyear}-${startmonth}-${startday} ${starthours}:${startminutes}:${startseconds}`;
// 获取当前日期
const now = new Date();
// 设置时间为当天的 23:59:59
const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
// 获取年、月、日
const year = endOfDay.getFullYear();
const month = String(endOfDay.getMonth() + 1).padStart(2, "0"); // 月份从 0 开始，需要 +1
const day = String(endOfDay.getDate()).padStart(2, "0"); // 补零
// 获取时、分、秒（固定为 23:59:59）
const hours = String(endOfDay.getHours()).padStart(2, "0"); // 补零
const minutes = String(endOfDay.getMinutes()).padStart(2, "0"); // 补零
const seconds = String(endOfDay.getSeconds()).padStart(2, "0"); // 补零
// 格式化为 YYYY-MM-DD HH:MM:SS
const endformattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
const state = reactive<any>({
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    taskStatusKey: [],
    time: "",
    startTime: startformattedTime || "",
    endTime: endformattedTime || ""
  },
  tableData: [],
  total: 0,
  isCancelShow: false,
  alarmId: "",
  taskStatusKeyList: [
    // { label: "全部", value: "" },
    { label: "隔离 ", value: "ISOLATION" },
    { label: "解隔离", value: "DISISOLATION" },
    { label: "已完成", value: "FINISH" },
    { label: "撤回", value: "END" }
  ],
  eqpTypeList: [],
  sumValue: {},
  contactNameList: [],
  contactNameListPlus: [],
  pageName: "list", // list列表页，detail详情页，edit编辑页
  currentData: {}, //当前详情/隔离/解隔离目标数据
  source: "list" // 页面来源
});
const {
  queryParams,
  tableData,
  total,
  isCancelShow,
  alarmId,
  taskStatusKeyList,
  eqpTypeList,
  sumValue,
  contactNameList,
  contactNameListPlus,
  pageName,
  currentData,
  source
} = toRefs(state);
watch(pageName, () => {
  if (pageName.value === "list") {
    source.value = "list";
    getNum();
    queryTable();
  }
});

// 计划开始时间;
const changeStartTime = () => {
  if (queryParams.value.startTime && queryParams.value.endTime) {
    if (queryParams.value.startTime > queryParams.value.endTime) {
      queryParams.value.endTime = queryParams.value.startTime;
    }
  }
};
// 计划结束时间
const changeEndTime = () => {
  if (queryParams.value.startTime && queryParams.value.endTime) {
    if (queryParams.value.startTime > queryParams.value.endTime) {
      queryParams.value.startTime = queryParams.value.endTime;
    }
  }
};
// 点击工单跳转详情
const clickEqpId = row => {
  pageName.value = "detail";
  currentData.value = row;
};
//创建人下拉
const queryRecipientIdSelect = async () => {
  contactNameList.value = await getEmployeeIdAndName();
};
//执行人下拉
const queryRecipientIdSelectPlus = async () => {
  contactNameListPlus.value = await getEmployeeIdAndName(["ERC&FP"]);
};
const getNum = async () => {
  sumValue.value = await getAlarmCount();
};
// 查询列表
const queryTable = async (res?) => {
  let params = JSON.parse(JSON.stringify(queryParams.value));
  const { time } = queryParams.value;
  // 点击今日解隔离工单
  if (res === "left") {
    const status = ["FINISH"];
    const data = await list({
      taskStatusKey: status,
      startTime: startformattedTime,
      endTime: endformattedTime,
      pageNum: 1,
      pageSize: queryParams.value.pageSize
    });
    resetTableList();
    queryParams.value.startTime = startformattedTime || "";
    queryParams.value.endTime = endformattedTime || "";
    queryParams.value.taskStatusKey = status;
    tableData.value = data?.data || [];
    total.value = data?.total;
  } else if (res === "middle") {
    // 点击今日未完成工单
    const status = ["ISOLATION", "DISISOLATION"];
    const data = await list({
      taskStatusKey: status,
      startTime: startformattedTime,
      endTime: endformattedTime,
      pageNum: 1,
      pageSize: queryParams.value.pageSize
    });
    resetTableList();
    queryParams.value.startTime = startformattedTime || "";
    queryParams.value.endTime = endformattedTime || "";
    queryParams.value.taskStatusKey = status;
    tableData.value = data?.data || [];
    total.value = data?.total;
  } else if (res === "right") {
    // 点击历史未执行工单
    const status = ["ISOLATION", "DISISOLATION"];
    const data = await list({
      taskStatusKey: status,
      startTime: "",
      endTime: startformattedTime,
      pageNum: 1,
      pageSize: queryParams.value.pageSize
    });
    resetTableList();
    queryParams.value.startTime = "";
    queryParams.value.endTime = startformattedTime;
    queryParams.value.taskStatusKey = status;
    tableData.value = data?.data || [];
    total.value = data?.total;
  } else {
    //点击查询按钮
    const data = await list(
      stringTrimOfParams({
        completedTimeStart: time && time[0] ? `${time[0]} 00:00:00` : "",
        completedTimeEnd: time && time[1] ? `${time[1]} 23:59:59` : "",
        ...params
      })
    );
    tableData.value = data?.data || [];
    total.value = data?.total;
  }
};
// 重置筛选条件列表
const resetTable = async () => {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    taskStatusKey: [],
    startTime: startformattedTime || "",
    endTime: endformattedTime || "",
    time: ""
  };
  queryTable();
};
//上方数据联动清空输入框
const resetTableList = async () => {
  queryParams.value = {
    workOrderNo: "",
    creator: "",
    executor: "",
    taskStatusKey: [],
    time: "",
    pageSize: 20,
    pageNum: 1
  };
};
const queryTree = async () => {
  const data: any = await searchTreeLedger({
    name: ""
  });
  eqpTypeList.value = data;
};
// 进入页面时触发
onMounted(async () => {
  getNum();
  queryTree();
  queryTable();
  queryRecipientIdSelect();
  queryRecipientIdSelectPlus();
});
const handleView = (row: any) => {
  alarmId.value = row.alarmId;
  isCancelShow.value = true;
  pageName.value = "edit";
  currentData.value = row;
};
</script>
<style lang="scss" scoped>
@import url("@/views/erc/scss/table-list.scss");

.equip-wrap-common {
  height: calc(100vh - 270px);

  .empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    height: 100%;
    padding-top: 200px;

    img {
      width: 160px;
      height: 160px;
    }

    p {
      font-size: 16px;
      color: #909399;
    }
  }
}

.banner {
  position: relative;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  padding: 16px;
  margin: 16px 0;
  background-color: #fff;
  border-radius: 8px;

  .left {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 33%;
    height: 72px;
    cursor: pointer;
    background: #fff linear-gradient(180deg, rgb(16 185 129 / 0%) 0%, rgb(16 185 129 / 8%) 100%);
    border: 1px solid #dcdcdc;
    border-radius: 4px;

    img {
      width: 58px;
      height: 61px;
    }

    .title {
      p:first-child {
        font-size: 14px;
        color: rgb(0 0 0 / 80%);
      }

      p:nth-child(2) {
        font-size: 22px;
        font-weight: 500;
        color: rgb(0 0 0 / 90%);
      }
    }
  }

  .middle {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 33%;
    height: 72px;
    margin: 0 16px;
    cursor: pointer;
    background: #fff linear-gradient(180deg, rgb(245 158 11 / 0%) 0%, rgb(245 158 11 / 8%) 100%);
    border: 1px solid #dcdcdc;
    border-radius: 4px;

    img {
      width: 58px;
      height: 61px;
    }

    .title {
      p:first-child {
        font-size: 14px;
        color: rgb(0 0 0 / 80%);
      }

      p:nth-child(2) {
        font-size: 22px;
        font-weight: 500;
        color: rgb(0 0 0 / 90%);
      }
    }
  }

  .right {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 33%;
    height: 72px;
    cursor: pointer;
    background: #fff linear-gradient(180deg, rgb(239 68 68 / 0%) 0%, rgb(239 68 68 / 8%) 100%);
    border: 1px solid #dcdcdc;
    border-radius: 4px;

    img {
      width: 61px;
      height: 60px;
    }

    .title {
      p:first-child {
        font-size: 14px;
        color: rgb(0 0 0 / 80%);
      }

      p:nth-child(2) {
        font-size: 22px;
        font-weight: 500;
        color: rgb(0 0 0 / 90%);
      }
    }
  }
}

.workOrderNo {
  color: #3b82f6;
  cursor: pointer;
}

.status {
  box-sizing: border-box;
  display: inline-flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 22px;
  padding: 3px 10px;
  font-size: 12px;
  line-height: 22px;
  border-radius: 4px;
}
</style>
